import asyncio
import time

async def a():
    print('Suspending a')
    await asyncio.sleep(3)
    print('Resuming a')


async def b():
    print('Suspending b')
    await asyncio.sleep(1)
    print('Resuming b')


def show_perf(func):
    print('*' * 20)
    start = time.perf_counter()
    asyncio.run(func())
    print(f'{func.__name__} Cost: {time.perf_counter() - start}')

async def s1():
    await a()
    await b()

async def s2():
    await asyncio.create_task(a())
    await asyncio.create_task(b())

async def c1():
    await asyncio.gather(a(), b())

async def c2():
    await asyncio.wait([a(), b()])

async def c3():
    task1 = asyncio.create_task(a())
    task2 = asyncio.create_task(b())
    await task1
    await task2

async def c4():
    task = asyncio.create_task(b())
    await a()
    await task

# asyncio.create_task是Python 3.7新增的高阶API，*是推荐的用法，其实你还可以用asyncio.ensure_future和loop.create_task：

async def c5():
    task = asyncio.ensure_future(b())
    await a()
    await task


async def c6():
    loop = asyncio.get_event_loop()
    task = loop.create_task(b())
    await a()
    await task

# 到这里，我们一共看到2种错误的，6种正确的写法。你学到了么？

if __name__ == '__main__':
    for f in (s1, s2, c1, c2, c3, c4, c5, c6):
        show_perf(f)

    # show_perf(s1)  #s1 Cost: 4.0024491
    # show_perf(s2)  #s2 Cost: 4.0008178999999995
    # show_perf(c1)  #c1 Cost: 3.0059607
    # show_perf(c2)  #c2 Cost: 3.0032052
    # show_perf(c3)  #c3 Cost: 3.0028164
    # show_perf(c4)  #c4 Cost: 3.0043765000000002
    # show_perf(c5)  #c5 Cost: 3.0021667
    # show_perf(c6)  #c6 Cost: 3.0026876


    print('完成')






